Define Functions to Make the Plots and Draw Braces¶

Starting with Valence Experiment¶

In [16]:
freq_plot(expt3_materials_forChi.loc['belinda_meeting','neg_mat'],
          10,
          title='Belinda Meeting Negative Scenario', 
          x_block_size=10, 
          y_block_size=10, 
          gap_size=0.5, 
          w=40, 
          h=30,
          brace_space_left=-0.3,
          brace_space_right=0.5)
In [17]:
freq_plot(expt3_materials_forChi.loc['belinda_meeting','pos_mat'],
          10,
          title='Belinda Meeting Positive Scenario', 
          x_block_size=10, 
          y_block_size=10, 
          gap_size=0.5, 
          w=40, 
          h=30,
          brace_space_left=-0.3,
          brace_space_right=.5)
In [ ]:
 
In [18]:
for mat in materials:
    for cond in ['pos_mat','neg_mat']:
        val_freq_plot(expt3_materials_forChi, mat, cond,
                  10,
                  title= str(mat+" "+cond), 
                  x_block_size=10, 
                  y_block_size=10, 
                  gap_size=0.5, 
                  w=40, 
                  h=30,
                  brace_space_left=-0.3,
                  brace_space_right=.5)
In [19]:
ds = expt3_materials_forChi
symbols = {'neither':['circle-open','black'],
           'neg':['circle','red'],
           'pos':['circle','yellowgreen']}  # 😀

#     print(sum(ds))

braces_lim={}
annot = {}

Xlim = Xlim

Ylim = (sum(ds)//Xlim)
Ylim = Ylim + (Ylim//y_block_size)*gap_size



Ypos = 0
Xpos = 0 ##change to zero for upwards
series = []


ygaps=np.arange(y_block_size, Ylim, y_block_size + gap_size)#[4,8+1,12+2,16+3,20+4,24+5,28+6,32+7,36+8,40+9]:  #43+10=53

braces_lim={}

if x_block_size < Xlim:
    Xlim = Xlim + (Xlim//x_block_size)*gap_size
    xgaps=np.arange(x_block_size, Xlim, x_block_size+gap_size)
    print(xgaps)
else:
    xgaps=np.array([])


for name, count in ds.iteritems():
    x = []
    y = []
    hover = []

#         first add name1 then name2
    for item in expt3[
        (expt3['material']==material) &
        (expt3['cond']==cond) &
        (expt3['val_code']==name)]['answer_text'].str.wrap(30).apply(lambda x: x.replace('\n', '<br>')):
        hover.append(item)

    for j in range(0, int(count)):

        if Xpos in xgaps:
            Xpos += gap_size

        if Xpos == Xlim:
            Xpos = 0
            Ypos += 1 ##change to positive for upwards

        if Ypos in ygaps:
            Ypos += gap_size

        y.append(Ypos)
        x.append(Xpos)
        Xpos += 1

        if Xpos == Xlim:
            Xpos = 0
            Ypos += 1 ##change to positive for upwards




    braces_lim[name]=(min(y)-0.5,max(y)+0.5)
    annot[name]=int(round((100*(count/ds.sum()))))

    series.append(go.Scatter(x=x, y=y,
                             hovertext = hover,
                             hoverinfo="text",
#                              mode='text', 
#                              text=[symbols[name][0]]*len(x),
#                              textfont= {
#                                     'size': 30,
#                                     'color': symbols[name][1]
#                                   },
                             mode='markers',
                             marker={'symbol': symbols[name][0], 
                                     'size': 12, 
                                     'color':symbols[name][1],
                                    'line':dict(
                                        color='black',
                                        width=0.4
                                    )
                                     },
                             name=f'{name} ({count})'
                            )
                        )


fig = go.Figure(dict(data=series, layout=go.Layout(
#     title={'text': title, 'x': 0.5, 'xanchor': 'center'},
    paper_bgcolor='rgba(255,255,255,1)',
    plot_bgcolor='rgba(0,0,0,0)',
    xaxis=dict(showgrid=False,zeroline= False, showline=False, visible=False, showticklabels=False),
    yaxis=dict(showgrid=False,zeroline= False, showline=False, visible=False, showticklabels=False),
)))

# ## Create the curly brace, thanks to https://stackoverflow.com/a/61454455 and https://stackoverflow.com/a/53383764/9600186 ##
draw_plotly_brace(fig=fig, yspan=(braces_lim['neg']), ylim=Ylim, xlim=Xlim, xx=brace_space_left, direction="left", spec_color='red')
draw_plotly_brace(fig=fig, yspan=(braces_lim['pos']), ylim=Ylim, xlim=Xlim, xx=Xlim-brace_space_right, direction="right",spec_color='yellowgreen')

fig.add_annotation(text=f"{annot['neg']}%",
                            x=-2, y=sum(braces_lim['neg'])/2,
                            showarrow=False,
                            textangle=-90,
                   font=dict(
                            family="Arial",
                            size=16,
                        )
                    )
fig.add_annotation(text=f"{annot['pos']}%",
                    x=Xlim+1, y=sum(braces_lim['pos'])/2,
                    showarrow=False,
                    textangle=-90,
                  font=dict(
                            family="Arial",
                            size=16,
                        )
                  )


fig.update_xaxes(
    scaleanchor = "y",
    scaleratio = 1,
)

fig.update_yaxes(
    range=[-1, Ylim+1], 
    constrain='domain'
  )

fig.update_layout(
    title=title,
    width=Xlim*w,
    height=Ylim*h,
    showlegend=False,
#remove some margin so the graph fits nicer in latex
    margin_l=0, #left margin
    margin_r=0, #right margin
    margin_b=0, #bottom margin
    margin_t=30, #top margin
)


#     print(ygaps)
#     print(Xlim)
#     print(Ylim)
#     print(fig.layout)
#     fig.write_image(file=f"3_output/{title}_fig.svg")



fig.update_layout(
    updatemenus=[
        dict(
            active=0,
            buttons=list([
                dict(label="None",
                     method="update",
                     args=[{"visible": [True, False, True, False]},
                           {"title": "Yahoo",
                            "annotations": []}]),
                dict(label="High",
                     method="update",
                     args=[{"visible": [True, True, False, False]},
                           {"title": "Yahoo High",
                            "annotations": high_annotations}]),
                dict(label="Low",
                     method="update",
                     args=[{"visible": [False, False, True, True]},
                           {"title": "Yahoo Low",
                            "annotations": low_annotations}]),
                dict(label="Both",
                     method="update",
                     args=[{"visible": [True, True, True, True]},
                           {"title": "Yahoo",
                            "annotations": high_annotations + low_annotations}]),
            ]),
        )
    ])

fig.show()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-19-a29ff05d49b4> in <module>
      9 annot = {}
     10 
---> 11 Xlim = Xlim
     12 
     13 Ylim = (sum(ds)//Xlim)

NameError: name 'Xlim' is not defined
In [ ]:
 
In [ ]:
def duo_freq_plot(data,Xlim,title='', x_block_size=20, y_block_size=4, gap_size=0.5, w=18, h=12.5,brace_space_left=0,brace_space_right=1):
    
    symbols = {'neither':['circle-open','black'],
               'neg':['circle','red'],
               'pos':['circle','yellowgreen']} 
    
    #make subplots
    fig = make_subplots(rows=1, cols=2,
                        subplot_titles=('neg_mat','pos_mat')
                        )
    
    for cond in ['neg_mat','pos_mat']:
#         make two separate plots/subplots
    
        ds = data.loc[cond]
         # 😀

    #     print(sum(ds))

        braces_lim={}
        annot = {}

        Xlim = Xlim

        Ylim = (sum(ds)//Xlim)
        Ylim = Ylim + (Ylim//y_block_size)*gap_size



        Ypos = 0
        Xpos = 0 ##change to zero for upwards
        series = []


        ygaps=np.arange(y_block_size, Ylim, y_block_size + gap_size)#[4,8+1,12+2,16+3,20+4,24+5,28+6,32+7,36+8,40+9]:  #43+10=53

        braces_lim={}

        if x_block_size < Xlim:
            Xlim = Xlim + (Xlim//x_block_size)*gap_size
            xgaps=np.arange(x_block_size, Xlim, x_block_size+gap_size)
            print(xgaps)
        else:
            xgaps=np.array([])

        for name, count in ds.iteritems():
            x = []
            y = []
            hover = []

    #         first add name1 then name2
            for item in expt3[
                (expt3['material']=='belinda_meeting') &
                (expt3['cond']==cond) &
                (expt3['val_code']==name)]['answer_text'].str.wrap(30).apply(lambda x: x.replace('\n', '<br>')):
                hover.append(item)

            for j in range(0, int(count)):

                if Xpos in xgaps:
                    Xpos += gap_size

                if Xpos == Xlim:
                    Xpos = 0
                    Ypos += 1 ##change to positive for upwards

                if Ypos in ygaps:
                    Ypos += gap_size

                y.append(Ypos)
                x.append(Xpos)
                Xpos += 1

                if Xpos == Xlim:
                    Xpos = 0
                    Ypos += 1 ##change to positive for upwards




            braces_lim[name]=(min(y)-0.5,max(y)+0.5)
            annot[name]=int(round((100*(count/data.sum()))))

            if cond=='neg_mat':
                fig.add_trace(go.Scatter(x=x, y=y,
                                     hovertext = hover,
                                     hoverinfo="text",
        #                              mode='text', 
        #                              text=[symbols[name][0]]*len(x),
        #                              textfont= {
        #                                     'size': 30,
        #                                     'color': symbols[name][1]
        #                                   },
                                     mode='markers',
                                     marker={'symbol': symbols[name][0], 
                                             'size': 12, 
                                             'color':symbols[name][1],
                                            'line':dict(
                                                color='black',
                                                width=0.4
                                            )
                                             },
                                     name=f'{name} ({count})'
                                    ), 
                              row=1, col=1)
            else:
                fig.add_trace(go.Scatter(x=x, y=y,
                                     hovertext = hover,
                                     hoverinfo="text",
        #                              mode='text', 
        #                              text=[symbols[name][0]]*len(x),
        #                              textfont= {
        #                                     'size': 30,
        #                                     'color': symbols[name][1]
        #                                   },
                                     mode='markers',
                                     marker={'symbol': symbols[name][0], 
                                             'size': 12, 
                                             'color':symbols[name][1],
                                            'line':dict(
                                                color='black',
                                                width=0.4
                                            )
                                             },
                                     name=f'{name} ({count})'
                                    ), 
                              row=1, col=2)


#     fig = go.Figure(dict(data=series, layout=go.Layout(
#     #     title={'text': title, 'x': 0.5, 'xanchor': 'center'},
#         paper_bgcolor='rgba(255,255,255,1)',
#         plot_bgcolor='rgba(0,0,0,0)',
#         xaxis=dict(showgrid=False,zeroline= False, showline=False, visible=False, showticklabels=False),
#         yaxis=dict(showgrid=False,zeroline= False, showline=False, visible=False, showticklabels=False),

    # ## Create the curly brace, thanks to https://stackoverflow.com/a/61454455 and https://stackoverflow.com/a/53383764/9600186 ##
#     draw_plotly_brace(fig=fig, yspan=(braces_lim['neg']), ylim=Ylim, xlim=Xlim, xx=brace_space_left, direction="left", spec_color='red')
#     draw_plotly_brace(fig=fig, yspan=(braces_lim['pos']), ylim=Ylim, xlim=Xlim, xx=Xlim-brace_space_right, direction="right" ,spec_color='yellowgreen')

#     fig.add_annotation(text=f"{annot['neg']}%",
#                                 x=-2, y=sum(braces_lim['neg'])/2,
#                                 showarrow=False,
#                                 textangle=-90,
#                        font=dict(
#                                 family="Arial",
#                                 size=16,
#                             )
#                         )
#     fig.add_annotation(text=f"{annot['pos']}%",
#                         x=Xlim+1, y=sum(braces_lim['pos'])/2,
#                         showarrow=False,
#                         textangle=-90,
#                       font=dict(
#                                 family="Arial",
#                                 size=16,
#                             )
#                       )

        
    fig.update_xaxes(
        scaleanchor = "y",
        scaleratio = 1,
    )
    
    fig.update_yaxes(
        range=[-1, Ylim+1], 
        constrain='domain'
      )
    
    fig.update_layout(
        title=title,
        width=Xlim*w,
        height=Ylim*h,
        showlegend=False,
    #remove some margin so the graph fits nicer in latex
        margin_l=0, #left margin
        margin_r=0, #right margin
        margin_b=0, #bottom margin
        margin_t=30, #top margin
    )

    
#     print(ygaps)
#     print(Xlim)
#     print(Ylim)
#     print(fig.layout)
#     fig.write_image(file=f"3_output/{title}_fig.svg")
    fig.show()
In [ ]:
duo_freq_plot(expt3_materials_forChi.loc['belinda_meeting'],
          10,
          title='Belinda Meeting Scenarios', 
          x_block_size=10, 
          y_block_size=10, 
          gap_size=0.5, 
          w=40, 
          h=30,
          brace_space_left=0,
          brace_space_right=.9)
In [ ]:
expt3_materials_forChi.loc['belinda_meeting'].loc['neg_mat']
In [ ]:
data=expt3_materials_forChi.loc['belinda_meeting']
Xlim=10
title='Belinda Meeting Scenarios'
x_block_size=10
y_block_size=10
gap_size=0.5
w=40
h=30
brace_space_left=0
brace_space_right=.9
    
symbols = {'neither':['circle-open','black'],
           'neg':['circle','red'],
           'pos':['circle','yellowgreen']} 

#make subplots
fig = make_subplots(rows=1, cols=2,
                    subplot_titles=('neg_mat','pos_mat')
                    )

for cond in ['neg_mat','pos_mat']:
#       make two separate plots/subplots

    ds = data.loc[cond]
     # 😀

#     print(sum(ds))

    braces_lim={}
    annot = {}

    Xlim = Xlim

    Ylim = (sum(ds)//Xlim)
    Ylim = Ylim + (Ylim//y_block_size)*gap_size

    Ypos = 0
    Xpos = 0 ##change to zero for upwards
    series = []

    ygaps=np.arange(y_block_size, Ylim, y_block_size + gap_size)#[4,8+1,12+2,16+3,20+4,24+5,28+6,32+7,36+8,40+9]:  #43+10=53

    braces_lim={}

    if x_block_size < Xlim:
        Xlim = Xlim + (Xlim//x_block_size)*gap_size
        xgaps=np.arange(x_block_size, Xlim, x_block_size+gap_size)
        print(xgaps)
    else:
        xgaps=np.array([])

    for name, count in ds.iteritems():
#         print(name, count)
        x = []
        y = []
        hover = []

#         first add name1 then name2
        for item in expt3[
            (expt3['material']=='belinda_meeting') &
            (expt3['cond']==cond) &
            (expt3['val_code']==name)]['answer_text'].str.wrap(30).apply(lambda x: x.replace('\n', '<br>')):
            hover.append(item)

        for j in range(0, int(count)):

            if Xpos in xgaps:
                Xpos += gap_size

            if Xpos == Xlim:
                Xpos = 0
                Ypos += 1 ##change to positive for upwards

            if Ypos in ygaps:
                Ypos += gap_size

            y.append(Ypos)
            x.append(Xpos)
            Xpos += 1

            if Xpos == Xlim:
                Xpos = 0
                Ypos += 1 ##change to positive for upwards




        braces_lim[name]=(min(y)-0.5,max(y)+0.5)
        annot[name]=int(round((100*(count/ds.sum()))))

        if cond=='neg_mat':
            fig.add_trace(go.Scatter(x=x, y=y,
                                 hovertext = hover,
                                 hoverinfo="text",
    #                              mode='text', 
    #                              text=[symbols[name][0]]*len(x),
    #                              textfont= {
    #                                     'size': 30,
    #                                     'color': symbols[name][1]
    #                                   },
                                 mode='markers',
                                 marker={'symbol': symbols[name][0], 
                                         'size': 12, 
                                         'color':symbols[name][1],
                                        'line':dict(
                                            color='black',
                                            width=0.4
                                        )
                                         },
                                 name=f'{name} ({count})'
                                ), 
                          row=1, col=1)
        else:
            fig.add_trace(go.Scatter(x=x, y=y,
                                 hovertext = hover,
                                 hoverinfo="text",
    #                              mode='text', 
    #                              text=[symbols[name][0]]*len(x),
    #                              textfont= {
    #                                     'size': 30,
    #                                     'color': symbols[name][1]
    #                                   },
                                 mode='markers',
                                 marker={'symbol': symbols[name][0], 
                                         'size': 12, 
                                         'color':symbols[name][1],
                                        'line':dict(
                                            color='black',
                                            width=0.4
                                        )
                                         },
                                 name=f'{name} ({count})'
                                ), 
                          row=1, col=2)


fig = go.Figure(dict(data=series, layout=go.Layout(
#     title={'text': title, 'x': 0.5, 'xanchor': 'center'},
    paper_bgcolor='rgba(255,255,255,1)',
    plot_bgcolor='rgba(0,0,0,0)',
    xaxis=dict(showgrid=False,zeroline= False, showline=False, visible=False, showticklabels=False),
    yaxis=dict(showgrid=False,zeroline= False, showline=False, visible=False, showticklabels=False),
)
                    )
               )

# ## Create the curly brace, thanks to https://stackoverflow.com/a/61454455 and https://stackoverflow.com/a/53383764/9600186 ##
# draw_plotly_brace(fig=fig, yspan=(braces_lim['neg']), ylim=Ylim, xlim=Xlim, xx=brace_space_left, direction="left", spec_color='red')
# draw_plotly_brace(fig=fig, yspan=(braces_lim['pos']), ylim=Ylim, xlim=Xlim, xx=Xlim-brace_space_right, direction="right" ,spec_color='yellowgreen')

# fig.add_annotation(text=f"{annot['neg']}%",
#                             x=-2, y=sum(braces_lim['neg'])/2,
#                             showarrow=False,
#                             textangle=-90,
#                    font=dict(
#                             family="Arial",
#                             size=16,
#                         )
#                     )
# fig.add_annotation(text=f"{annot['pos']}%",
#                     x=Xlim+1, y=sum(braces_lim['pos'])/2,
#                     showarrow=False,
#                     textangle=-90,
#                   font=dict(
#                             family="Arial",
#                             size=16,
#                         )
#                   )

    
# fig.update_xaxes(
#     scaleanchor = "y",
#     scaleratio = 1,
# )

# fig.update_yaxes(
#     range=[-1, Ylim+1], 
#     constrain='domain'
#   )

# fig.update_layout(
#     title=title,
#     width=Xlim*w,
#     height=Ylim*h,
#     showlegend=False,
# #remove some margin so the graph fits nicer in latex
#     margin_l=0, #left margin
#     margin_r=0, #right margin
#     margin_b=0, #bottom margin
#     margin_t=30, #top margin
# )


# print(ygaps)
# print(Xlim)
# print(Ylim)
# print(fig.layout)
# fig.write_image(file=f"3_output/{title}_fig.svg")
fig.show()
In [ ]:
int(round((100*(24./data.sum()))))
In [ ]:
 
In [ ]:
# title = 'Valenced Outcomes'

# ds = expt3_materials_forChi.loc['belinda_meeting'].sum()
# symbols = {'neither':['circle-open','black'],
#            'neg':['circle','red'],
#            'pos':['circle','yellowgreen']}  # 😀

# print(sum(ds))

# Xlim = 10
# Ylim = 10
# Xpos = 0
# Ypos = Ylim ##change to zero for upwards
# series = []
# for name, count in ds.iteritems():
#     x = []
#     y = []
#     for j in range(0, int(count)):
#         if Xpos == Xlim:
#             Xpos = 0
#             Ypos -= 1 ##change to positive for upwards
#         x.append(Xpos)
#         y.append(Ypos)
#         Xpos += 1
#     series.append(go.Scatter(x=x, y=y, 
# #                              mode='text', 
# #                              text=[symbols[name][0]]*len(x),
# #                              textfont= {
# #                                     'size': 30,
# #                                     'color': symbols[name][1]
# #                                   },
#                              mode='markers',
#                              marker={'symbol': symbols[name][0], 
#                                      'size': 6, 
#                                      'color':symbols[name][1],
#                                     'line':dict(
#                                         color='black',
#                                         width=0.5
#                                     )
#                                      },
#                              name=f'{name} ({count})'
#                             )
#                         )


# fig = go.Figure(dict(data=series, layout=go.Layout(
#     title={'text': title, 'x': 0.5, 'xanchor': 'center'},
# #     paper_bgcolor='rgba(255,255,255,1)',
# #     plot_bgcolor='rgba(0,0,0,0)',
# #     xaxis=dict(showgrid=False,zeroline= False, showline=False, visible=False, showticklabels=False),
# #     yaxis=dict(showgrid=False,zeroline= False, showline=False, visible=False, showticklabels=False),
# )))

# ## Create the curly brace, thanks to https://stackoverflow.com/a/61454455 and https://stackoverflow.com/a/53383764/9600186 ##
# draw_plotly_brace(fig=fig, yspan=(19,43.5), ylim=Ylim, xlim=Xlim, xx=0.5, direction="left", spec_color='red')
# draw_plotly_brace(fig=fig, yspan=(0,15), ylim=Ylim, xlim=Xlim, xx=39, direction="right",spec_color='yellowgreen')

# fig.add_annotation(text="Neg: 56.74%",
#                    x=-4, y=31,
#                    showarrow=False,
#                    textangle=-90)
# fig.add_annotation(text="Pos: 35.10%",
#                    x=42.2, y=7.5,
#                    showarrow=False,
#                    textangle=90)

# # fig.add_annotation(x=14, y=43,
# #         xref="x",
# #         yref="y",
# #         text="She got mugged.",
# #         showarrow=True,
# #         align="center",
# #         arrowhead=1,
# #         arrowsize=1,
# #         arrowwidth=2,
# #         arrowcolor="#636363",
# #         ax=20,
# #         ay=-30,
# #         bordercolor="#c7c7c7",
# #         borderwidth=2,
# #         borderpad=4,
# #         bgcolor="#ffffff",
# #         opacity=0.8)


# # fig.add_annotation(x=27, y=0,
# #         xref="x",
# #         yref="y",
# #         text="There was a sale.",
# #         showarrow=True,
# #         align="center",
# #         arrowhead=1,
# #         arrowsize=1,
# #         arrowwidth=2,
# #         arrowcolor="#636363",
# #         ax=20,
# #         ay=30,
# #         bordercolor="#c7c7c7",
# #         borderwidth=2,
# #         borderpad=4,
# #         bgcolor="#ffffff",
# #         opacity=0.8)


# fig.update_layout(
#     width=500,
#     height=700,
#     showlegend=False)

# fig.update_xaxes(range=[-5, 43])
# fig.update_yaxes(
#     scaleanchor = "x",
#     scaleratio = 1,
#       )

# fig.show()
In [ ]:
fig.update_layout(
    updatemenus=[
        dict(
            active=0,
            buttons=list([
                dict(label="None",
                     method="update",
                     args=[{"visible": [True, False, True, False]},
                           {"title": "Yahoo",
                            "annotations": []}]),
                dict(label="High",
                     method="update",
                     args=[{"visible": [True, True, False, False]},
                           {"title": "Yahoo High",
                            "annotations": high_annotations}]),
                dict(label="Low",
                     method="update",
                     args=[{"visible": [False, False, True, True]},
                           {"title": "Yahoo Low",
                            "annotations": low_annotations}]),
                dict(label="Both",
                     method="update",
                     args=[{"visible": [True, True, True, True]},
                           {"title": "Yahoo",
                            "annotations": high_annotations + low_annotations}]),
            ]),
        )
    ])
In [ ]:
 
In [ ]: